<?php
/**
 * Created by PhpStorm
 * User: hon(陈烁临) qq: 2275604210
 * Date: 2022/1/11
 * Time: 3:23 下午
 */

namespace App\Traits;


trait ResponseTrait
{
    private $resp_result_success = 1;
    private $resp_result_error = 0;
    private $resp_code_success = 0;

    protected function resp($data, $httpCode = 200, $contentType = 'application/json') {
        $resp = response($data, $httpCode)
            ->header('Content-Type', $contentType);

        return $resp;
    }

    protected function respSuccess($data = [], $total = 0, $msg = "查询成功") {
        return $this->resp([
            'result'    => $this->resp_result_success,
            'msg'       => $msg,
            'errorcode' => $this->resp_code_success,
            'total'     => $total,
            'data'      => $data,
            'code'      => $this->resp_code_success
        ]);
    }

    protected function respSuccessData($data = [], $msg = "查询成功") {
        return $this->resp([
            'result'    => $this->resp_result_success,
            'msg'       => $msg,
            'errorcode' => $this->resp_code_success,
            'data'      => $data,
        ]);
    }

    protected function respSuccessPage($data, $msg = "查询成功") {
        return $this->resp([
            'result'    => $this->resp_result_success,
            'msg'       => $msg,
            'errorcode' => $this->resp_code_success,
            'total'     => $data['total'],
            'data'      => $data['data'],
        ]);
    }

    protected function respSuccessMsg($msg = "查询成功") {
        return $this->resp([
            'result'    => $this->resp_result_success,
            'msg'       => $msg,
            'errorcode' => $this->resp_code_success,
            'data'      => null,
            'code'      => $this->resp_code_success
        ]);
    }

    protected function respError($msg = "系统出现异常。", $error_code = 0) {
        return $this->resp([
            'result'    => $this->resp_result_error,
            'msg'       => $msg,
            'errorcode' => $error_code,
            'code'      => $error_code
        ],$httpCode=500);
    }

    protected function respDownload($filePath, $fileName, $contentType, $deleteFileAfterSend = true) {
        $headers = [
            'Content-Type: ' . $contentType,
        ];
        return response()
            ->download($filePath, $fileName, $headers)
            ->deleteFileAfterSend($deleteFileAfterSend);
    }
}
